{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "be5212e7",
   "metadata": {},
   "source": [
    "## 导入数据"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "id": "e6c0b995",
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import pandas as pd\n",
    "from sklearn.datasets import load_iris\n",
    "from sklearn.model_selection import train_test_split, GridSearchCV, cross_val_score\n",
    "from sklearn.linear_model import LogisticRegression as LR\n",
    "from sklearn.preprocessing import StandardScaler\n",
    "import warnings \n",
    "warnings.filterwarnings(\"ignore\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "89e506a0",
   "metadata": {},
   "source": [
    "## 切分数据集"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "7a988ef2",
   "metadata": {},
   "outputs": [],
   "source": [
    "X=load_iris().data\n",
    "Y=load_iris().target"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "c1250451",
   "metadata": {},
   "outputs": [],
   "source": [
    "Xtrain,Xtest,Ytrain,Ytest=train_test_split(X,Y,test_size=0.3,random_state=200)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f0bbd6c2",
   "metadata": {},
   "source": [
    "## 标准化处理"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "id": "e4ad896a",
   "metadata": {},
   "outputs": [],
   "source": [
    "std=StandardScaler().fit(Xtrain)\n",
    "Xtrain_=std.transform(Xtrain)\n",
    "Xtest_=std.transform(Xtest)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9ec6559c",
   "metadata": {},
   "source": [
    "## 训练"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 60,
   "id": "4d445503",
   "metadata": {},
   "outputs": [],
   "source": [
    "l1=[]\n",
    "l2=[]\n",
    "l1test=[]\n",
    "l2test=[]\n",
    "\n",
    "l1p={'C':list(np.linspace(0.05,1,19)),\n",
    "           'solver':['liblinear']} #l1正则化仅两种solver\n",
    "\n",
    "l2p={'C':list(np.linspace(0.05,1,19)),\n",
    "           'solver':['liblinear','sag','newton-cg','lbfgs']}\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 61,
   "id": "3f2a975a",
   "metadata": {},
   "outputs": [],
   "source": [
    "model_l1=LR(penalty='l1',max_iter=1000)\n",
    "model_l2=LR(penalty='l2',max_iter=1000)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 62,
   "id": "63f4248c",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(GridSearchCV(cv=5, estimator=LogisticRegression(max_iter=1000, penalty='l1'),\n",
       "              param_grid={'C': [0.05, 0.10277777777777777, 0.15555555555555556,\n",
       "                                0.20833333333333331, 0.2611111111111111,\n",
       "                                0.3138888888888889, 0.36666666666666664,\n",
       "                                0.41944444444444445, 0.4722222222222222, 0.525,\n",
       "                                0.5777777777777778, 0.6305555555555556,\n",
       "                                0.6833333333333333, 0.7361111111111112,\n",
       "                                0.788888888888889, 0.8416666666666667,\n",
       "                                0.8944444444444445, 0.9472222222222223, 1.0],\n",
       "                          'solver': ['liblinear']}),\n",
       " GridSearchCV(cv=5, estimator=LogisticRegression(max_iter=1000),\n",
       "              param_grid={'C': [0.05, 0.10277777777777777, 0.15555555555555556,\n",
       "                                0.20833333333333331, 0.2611111111111111,\n",
       "                                0.3138888888888889, 0.36666666666666664,\n",
       "                                0.41944444444444445, 0.4722222222222222, 0.525,\n",
       "                                0.5777777777777778, 0.6305555555555556,\n",
       "                                0.6833333333333333, 0.7361111111111112,\n",
       "                                0.788888888888889, 0.8416666666666667,\n",
       "                                0.8944444444444445, 0.9472222222222223, 1.0],\n",
       "                          'solver': ['liblinear', 'sag', 'newton-cg', 'lbfgs']}))"
      ]
     },
     "execution_count": 62,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "GS_l1=GridSearchCV(model_l1,l1p,cv=5)\n",
    "GS_l2=GridSearchCV(model_l2,l2p,cv=5)\n",
    "GS_l1.fit(Xtrain_,Ytrain),GS_l2.fit(Xtest_,Ytest)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 63,
   "id": "5fb9ba39",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(0.9142857142857143, 0.9333333333333333)"
      ]
     },
     "execution_count": 63,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "GS_l1.best_score_,GS_l2.best_score_\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 64,
   "id": "23a50cb8",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "({'C': 0.8416666666666667, 'solver': 'liblinear'},\n",
       " {'C': 0.05, 'solver': 'liblinear'})"
      ]
     },
     "execution_count": 64,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "GS_l1.best_params_,GS_l2.best_params_\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e3e347bc",
   "metadata": {},
   "source": [
    "## 实例化"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 65,
   "id": "1da83596",
   "metadata": {},
   "outputs": [],
   "source": [
    "shili_l1=LR(penalty='l1',max_iter=1000,C=GS_l1.best_params_['C'],solver=GS_l1.best_params_['solver'])\n",
    "shili_l2=LR(penalty='l2',max_iter=1000,C=GS_l2.best_params_['C'],solver=GS_l2.best_params_['solver'])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 66,
   "id": "373b0ec8",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(0.8761904761904762, 0.9777777777777777)"
      ]
     },
     "execution_count": 66,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "shili_l1.fit(Xtrain_,Ytrain)\n",
    "shili_l1.fit(Xtest_,Ytest)\n",
    "shili_l1.score(Xtrain_,Ytrain),shili_l1.score(Xtest_,Ytest)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 67,
   "id": "9a085d9b",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(0.8, 0.9333333333333333)"
      ]
     },
     "execution_count": 67,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "shili_l2.fit(Xtrain_,Ytrain)\n",
    "shili_l2.fit(Xtest_,Ytest)\n",
    "shili_l2.score(Xtrain_,Ytrain),shili_l2.score(Xtest_,Ytest)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "80a09d47",
   "metadata": {},
   "source": [
    "## 精确"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 94,
   "id": "1dd18b3c",
   "metadata": {},
   "outputs": [],
   "source": [
    "shilil1_df=pd.DataFrame(shili_l1.predict(Xtrain_).reshape(-1,1))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 96,
   "id": "52cb4b39",
   "metadata": {},
   "outputs": [],
   "source": [
    "shilil1_df['zhenshi']=Ytrain"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 104,
   "id": "94297681",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "True     92\n",
       "False    13\n",
       "dtype: int64"
      ]
     },
     "execution_count": 104,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "(shilil1_df.iloc[:,0]==shilil1_df.iloc[:,1]).value_counts()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 106,
   "id": "ece1cb6a",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "True     84\n",
       "False    21\n",
       "dtype: int64"
      ]
     },
     "execution_count": 106,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "shilil2_df=pd.DataFrame(shili_l2.predict(Xtrain_).reshape(-1,1))\n",
    "shilil2_df['zhenshi']=Ytrain\n",
    "(shilil2_df.iloc[:,0]==shilil2_df.iloc[:,1]).value_counts()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f002d65f",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "59f99159",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.4"
  },
  "toc": {
   "base_numbering": 1,
   "nav_menu": {},
   "number_sections": true,
   "sideBar": true,
   "skip_h1_title": false,
   "title_cell": "Table of Contents",
   "title_sidebar": "Contents",
   "toc_cell": false,
   "toc_position": {},
   "toc_section_display": true,
   "toc_window_display": false
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
